package com.changan;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageUtils {

    public static float[] preprocess(File imageFile) throws IOException {
        BufferedImage img = ImageIO.read(imageFile);
        // 调整大小为 224x224（ResNet 输入尺寸）
        Image scaledImage = img.getScaledInstance(224, 224, Image.SCALE_SMOOTH);
        BufferedImage scaledBufferedImage = new BufferedImage(224, 224, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = scaledBufferedImage.createGraphics();
        g.drawImage(scaledImage, 0, 0, null);
        g.dispose();

        float[] imageData = new float[3 * 224 * 224]; // RGB channels
        int idx = 0;
        for (int y = 0; y < 224; y++) {
            for (int x = 0; x < 224; x++) {
                int pixel = scaledBufferedImage.getRGB(x, y);
                int r = (pixel >> 16) & 0xFF;
                int gVal = (pixel >> 8) & 0xFF;
                int b = pixel & 0xFF;

                // Normalize to [0, 1] and apply ImageNet normalization
                imageData[idx++] = ((r / 255.0f) - 0.485f) / 0.229f;
                imageData[idx++] = ((gVal / 255.0f) - 0.456f) / 0.224f;
                imageData[idx++] = ((b / 255.0f) - 0.406f) / 0.225f;
            }
        }
        return imageData;
    }
}